package com.xb.filter;

import com.xb.entity.User;
import com.xb.service.UserService;
import com.xb.utils.CookieUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {

    private UserService userService = new UserService();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 统一处理乱码
        request.setCharacterEncoding("UTF-8");

        String requestURI = request.getRequestURI();

        String targetName = requestURI.substring(requestURI.lastIndexOf("/"));

        if (
                requestURI.equals("/checkCode.jsp") ||
                        requestURI.equals("/forget.jsp") ||
                        requestURI.equals("/index.jsp") ||
                        requestURI.equals("/register.jsp") ||
                        requestURI.equals("/taglib.jsp") ||
                        requestURI.startsWith("/bootstrap/") ||
                        requestURI.startsWith("/css/") ||
                        requestURI.startsWith("/fonts/") ||
                        requestURI.startsWith("/img/") ||
                        requestURI.startsWith("/js/") ||
                        requestURI.startsWith("/vendor/") ||
                        targetName.equals("/login") ||
                        targetName.equals("/register") ||
                        targetName.equals("/home") ||
                        targetName.equals("/wx_login") ||
                        targetName.equals("/checkUsername") ||
                        targetName.equals("/checkEmail")
        ) {

            // 以上资源就算没有登录也可以访问
            filterChain.doFilter(request, response);
            return;
        }


        // 受限资源，要看是否登录了
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");

        if (loginUser != null) {

            // 虽然是受限资源，但是登录了
            filterChain.doFilter(request, response);
            return;
        }

        // 虽然session没有，但是还要判断一下Cookie是否有用户信息
        Cookie userIdCookie = CookieUtils.getCookie(request, "userId");

        if (userIdCookie != null) {
            // 虽然是受限资源，并且session也没有，但是cookie有用户的信息

            // 获取cookie的信息
            Long userId = Long.parseLong(userIdCookie.getValue());
            User user = userService.findById(userId);

            // 手动将用户信息存入session
            session.setAttribute("loginUser", user);

            // 将Cookie续期为新的7天
            Cookie cookie = new Cookie("userId", user.getId() + "");
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie);

            // 放行请求
            filterChain.doFilter(request,response);

            return;
        }


        // 受限资源，但是没有登录
        response.sendRedirect("/index.jsp");


    }

    @Override
    public void destroy() {

    }
}
